package com.hty.locusmap;

import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class GPXList extends Activity {

	ListView listView;
	EditText editText_search;
	ImageButton imageButton_clear;
	SimpleAdapter adapter;
	ArrayList<HashMap<String, Object>> list_file = new ArrayList<>();
	final String dir = Environment.getExternalStorageDirectory().getPath() + "/LocusMap/";
	SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
	InputMethodManager IMM;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gpxlist);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		IMM = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		listView = findViewById(R.id.listView);
		editText_search = findViewById(R.id.editText);
		editText_search.addTextChangedListener(new EditChangedListener());
		imageButton_clear = findViewById(R.id.imageButton_clear);
		imageButton_clear.setVisibility(View.GONE);
		imageButton_clear.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				editText_search.setText("");
			}
		});
		adapter = new SimpleAdapter(this, list_file, R.layout.item, new String[] { "icon", "name", "size", "time" }, new int[] { R.id.imageView_icon, R.id.textView_name, R.id.textView_size, R.id.textView_time });
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				String filename = ((TextView) arg1.findViewById(R.id.textView_name)).getText().toString();
				Log.e(Thread.currentThread().getStackTrace()[2] + "", filename);
				String filepath = Environment.getExternalStorageDirectory().getPath() + "/LocusMap/" + filename;
				if (filename.toLowerCase().endsWith(".gpx")) {
					if (RWXML.read1(filepath) != null) {
						Intent intent = new Intent(GPXList.this, HistoryLocus.class);
						intent.putExtra("filename", filename);
						startActivity(intent);
					} else {
						String text;
						if (filepath.equals(MainApplication.wfp)) {
							text = filename + " 刚创建，即将写入数据！";
						} else {
							File file = new File(filepath);
							file.delete();
							text = filename + " 是空文档，自动删除！";
							int position = listView.getFirstVisiblePosition();
							genList(editText_search.getText().toString());
							listView.setSelection(position);
						}
						Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		listView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
				AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
				String title = ((TextView) info.targetView.findViewById(R.id.textView_name)).getText().toString();
				menu.setHeaderTitle(title);
				menu.add(0, 0, 0, "分享");
				menu.add(0, 1, 1, "重命名");
				menu.add(0, 2, 2, "删除");
			}
		});
		genList("");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "刷新");
		menu.add(0, 1, 1, "关闭");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
			case 0:
				int position = listView.getFirstVisiblePosition();
				genList(editText_search.getText().toString());
				listView.setSelection(position);
				break;
			case 1:
				finish();
				startActivity(new Intent(GPXList.this, MenuActivity.class));
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		final String filename = ((TextView) info.targetView.findViewById(R.id.textView_name)).getText().toString();
		final String filepath = MainApplication.dir_gpx + filename;
		switch (item.getItemId()) {
			case 0:
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_SEND);
				intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(filepath)));
				intent.setType("*/*");
				startActivity(Intent.createChooser(intent, "分享 " + filename));
				break;
			case 1:
				if (!filepath.equals(MainApplication.wfp)) {
					final EditText editText = new EditText(GPXList.this);
					editText.setText(filename);
					AlertDialog.Builder dialog = new AlertDialog.Builder(GPXList.this);
					dialog.setTitle("重命名").setView(editText);
					dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							IMM.hideSoftInputFromWindow(editText.getWindowToken(), 0);
							File file = new File(filepath);
							String filename1 = editText.getText().toString();
							String filepath1 = MainApplication.dir_gpx + filename1;
							File file1 = new File(filepath1);
							if (file.renameTo(file1)) {
								genList(editText_search.getText().toString());
							} else {
								new AlertDialog.Builder(GPXList.this).setIcon(android.R.drawable.stat_notify_error).setTitle("操作").setMessage("重命名失败\n" + filepath1).setPositiveButton("确定", null);
							}
						}
					});
					dialog.setNegativeButton("取消", null);
					dialog.show();
				} else {
					new AlertDialog.Builder(GPXList.this).setIcon(R.drawable.warn).setTitle("重命名操作").setMessage("此文件正在记录中，无法重命名！").setPositiveButton("确定", null);
				}
				break;
			case 2:
				new AlertDialog.Builder(GPXList.this).setIcon(R.drawable.warn).setTitle("删除操作").setMessage("此步骤不可还原，确定删除\n" + filename + " ？")
						.setPositiveButton("是", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								String text;
								if (filepath.equals(MainApplication.wfp)) {
									text = filename + "正在写入数据，禁止删除！";
								} else {
									File file = new File(filepath);
									if (file.delete()) {
										text = filename + " 删除成功";
										genList(editText_search.getText().toString());
									} else {
										text = filename + " 删除失败";
									}
								}
								Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
							}
						})
						.setNegativeButton("否", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
							}
						}).show();
				break;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(new Intent(GPXList.this, MenuActivity.class));
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		super.onResume();
		int position = listView.getFirstVisiblePosition();
		genList(editText_search.getText().toString());
		listView.setSelection(position);
	}

	class ComparatorTimeDesc implements Comparator<File> {
		@Override
		public int compare(File f1, File f2) {
			long diff = f2.lastModified() - f1.lastModified();
			if (diff > 0)
				return 1;
			else if (diff == 0)
				return 0;
			else
				return -1;
		}
	}

	void genList(final String s) {
		list_file.clear();
		File file = new File(dir);
		File[] files = file.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File f, String name) {
				if (s.equals(""))
					return name.endsWith(".gpx");
				else
					return name.endsWith(".gpx") && name.contains(s);
			}
		});
		Arrays.sort(files, new ComparatorTimeDesc());
		Log.e(Thread.currentThread().getStackTrace()[2] + "", files.toString());
		for (File file1 : files) {
			HashMap<String, Object> listItem = new HashMap<String, Object>();
			String suffix = file1.getName().substring(file1.getName().lastIndexOf(".") + 1).toLowerCase();
			if (suffix.equals("gpx")) {
				listItem.put("icon", R.drawable.gpx);
			} else {
				listItem.put("icon", R.drawable.file);
			}
			listItem.put("name", file1.getName());
			listItem.put("size", Formatter.formatFileSize(this, file1.length()));
			listItem.put("time", SDF.format(new Date(file1.lastModified())));
			list_file.add(listItem);
		}
		adapter.notifyDataSetChanged();
		setTitle("轨迹列表 " + files.length);
	}

	class EditChangedListener implements TextWatcher {
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,int after) {

		}
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}
		@Override
		public void afterTextChanged(Editable s) {
			if(s.toString().equals("")){
				imageButton_clear.setVisibility(View.GONE);
			}else{
				imageButton_clear.setVisibility(View.VISIBLE);
			}
			genList(s.toString());
		}
	}

}